package util;

import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 数据库连接工具类
 */
public class DBUtil {
    // 单例模式
    private DBUtil() {
    }

    // 1.获得数据源  DataSource
    private static volatile MysqlDataSource dataSource;
    //private static volatile Connection connection;
    private static MysqlDataSource getDataSource() {/*懒汉模式，使用时再创建*/
        if(dataSource == null) {
            synchronized (DBUtil.class) {
                if(dataSource == null) {
                    dataSource = new MysqlDataSource();
                    dataSource.setURL("jdbc:mysql://127.0.0.1:3306/Person?serverTimezone=UTC&characterEncoding=utf8&useSSL=false");
                    dataSource.setUser("root");
                    dataSource.setPassword("root");
                }
            }
        }
        return dataSource;
    }

    // 2.得到连接 Connection
    public static Connection getConnection() throws SQLException {
        MysqlDataSource dataSource = getDataSource();
        return dataSource.getConnection();
    }

    // 2. 关闭资源
    public static void close(PreparedStatement statement, Connection connection) throws SQLException {
        if(statement != null) statement.close();
        if(connection != null) connection.close();
    }
}